package com.medreams.controller;

import com.medreams.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class TestController {

    @RequestMapping(path = "/hello")
    public ModelAndView hello(User user){
        ModelAndView modelAndView = new ModelAndView();
        for (String s : user.getLike()) {
            System.out.println(s);
        }
        //传对象object
        modelAndView.addObject("user",user);
        //传值
        modelAndView.addObject("username","hello");
        //设置模板
        modelAndView.setViewName("success");
        return modelAndView;
//        System.out.println(user);
//        User{username='admin', age=12, likes=[Like{likename='java'}, Like{likename='golang'}], like=[篮球, 足球]}
//        return "success";
    }

//    这里的json 能够直接接收和返回转化是加入了json的坐标 在pom.xml文件中 若没有需要 在获取时 @RequestBody String body 需要自己去查找
    @RequestMapping(value = "jsonTest",method = {RequestMethod.POST})
    public @ResponseBody User getUserInfo(@RequestBody User user){
        System.out.println(user);
        return user;
    }

    @RequestMapping(value = "upload",method = {RequestMethod.POST})
//    MultipartFile upload 需要与表单中upload相同
    public @ResponseBody ModelAndView uploadFile(HttpServletRequest request, MultipartFile upload){
        //设置上传路径
        String realPath = request.getSession().getServletContext().getRealPath("/images");
        File file = new File(realPath);
        if (!file.exists()){
            //如果文件夹不存在则创建
            file.mkdirs();
        }

        //获取上传原始的文件名
        String filename = upload.getOriginalFilename();
        //设置唯一的文件名
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //拼接成新的文件名
        filename = uuid+"_"+filename;
        //最终上传文件
        try {
            upload.transferTo(new File(realPath,filename));
        } catch (IOException e) {
            e.printStackTrace();
        }

        Map<String,Object> map = new HashMap<>();
        map.put("code",200);
        map.put("message","上传成功");
        //将map转化为json字符串返回
        return new ModelAndView(new MappingJackson2JsonView(),map);
    }

}
